package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.apache.commons.lang3.StringUtils;

import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * Created with IntelliJ IDEA.
 * User: zjz
 * Date: 2022/07/09 16:59
 * Description:
 * Version: V1.0
 */
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {
    /**
     * 盐值，混淆密码
     */
    private final static String SALT = "zjz";


    @Resource
    private EmployeeMapper employeeMapper;



    @Override
    public R<String> save(Employee employee, HttpServletRequest request) {
        //1、员工对象非空
        if (employee == null){
            return R.error("员工信息为空");
        }
        String username = employee.getUsername();

        // 2、员工信息非空
        if (StringUtils.isAnyBlank(username, employee.getName(),employee.getPhone(),employee.getIdNumber())){
            return R.error("员工信息不齐全");
        }

        //3、校验用户账号和密码的长度
        //todo 校验name为中文姓名
        if (username.length() < 4){
            return R.error("员工账号长度不合法");
        }
        //4、校验用户是否包含特殊字符
        String validPattern = "[\\n`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。， 、？✅\\uD83D\\uDFE7]";
        if (validPattern.matches(username)){
            return R.error("账号包含非法字符");
        }

        //5、账号不能重复
        QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        Integer count = employeeMapper.selectCount(queryWrapper);
        if (count > 0){
            return R.error("账号已经存在");
        }

        //6、身份证号不能重复
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id_number",employee.getIdNumber());
        count = employeeMapper.selectCount(queryWrapper);
        if (count > 0){
            return R.error("身份证号已存在");
        }

        //7、设置初始密码为123456，并且加密
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));

        //8、设置创建时间、更改时间
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());

        //9、获取当前登录员工的id
        Long empId = (Long) request.getSession().getAttribute("employee");

        //10、设置创建人、修改人
//        employee.setCreateUser(empId);
//        employee.setUpdateUser(empId);
        //11、新增员工
        boolean save = this.save(employee);
        if (!save){
            return R.error("新增失败");
        }
        return R.success("新增员工成功");
    }

    /**
     * 员工登录
     * @param username 员工姓名
     * @param password 密码
     * @param request request
     * @return
     */
    @Override
    public R<Employee> login(String username, String password, HttpServletRequest request) {

        // 1、账号密码非空
        if (StringUtils.isAnyBlank(username,password)){
            return R.error("用户名或密码不能为空");
        }
        //2、校验用户账号和密码的长度
        if (username.length() < 4 || password.length() < 6){
            return R.error("用户名或密码长度不合法");
        }
        //3、校验用户是否包含特殊字符
        String validPattern = "[\\n`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。， 、？✅\\uD83D\\uDFE7]";
        if (validPattern.matches(username)){
            return R.error("用户名输入非法字符");
        }
        //4、将密码转成MD5与数据库中对应的账号的密码进行比对
        //todo 暂时不加盐值
//        String mdsPassword = DigestUtils.md5DigestAsHex((SALT + password).getBytes());
        String mdsPassword = DigestUtils.md5DigestAsHex(password.getBytes());
            //4.1查询用户
        QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        queryWrapper.eq("password",mdsPassword);
        Employee employee = employeeMapper.selectOne(queryWrapper);
                //4.1.1用户不存在返回失败信息
        if (employee == null){
            return R.error("账号或密码错误");
        }
                //4.1.2用户存在则进行下一步
            //4.2比对不成功则返回失败信息

            //4.3比对成功则进行下一步


        //5、查看用户状态，如果为禁用状态则返回禁用状态结果
        if (employee.getStatus() == 0){
            return R.error("账号已禁用");
        }

        //6、如果不是禁用状态，记录用户登录态(session)，返回脱敏后的用户信息
        request.getSession().setAttribute("employee",employee.getId());
        //用户脱敏
        Employee safetyEmployee = getSafetyEmployee(employee);

        return R.success(safetyEmployee);
    }


    /**
     * 员工退出
     * @param request request
     * @return
     */
    @Override
    public R<String> logout(HttpServletRequest request) {
        //1、清理session中保存的当前登录员的id
        request.getSession().removeAttribute("employee");

        return R.success("退出成功");
    }

    @Override
    public R<Page> page(int page, int pageSize, String name) {
        if (page <= 0 || pageSize <= 0){
            return R.error("参数错误");
        }
        //构造分页构造器
        Page pageInfo = new Page(page,pageSize);

        //构造条件构造器
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper();
        //添加过滤条件
        queryWrapper.like(StringUtils.isNoneEmpty(name),Employee::getName,name);
        //添加排序条件
        queryWrapper.orderByDesc(Employee::getUpdateTime);
        //执行查询
        this.page(pageInfo,queryWrapper);
        return R.success(pageInfo);
    }


    public Employee getSafetyEmployee(Employee originalEmployee){
        if (originalEmployee == null){
            return null;
        }
        Employee safetyUser =new Employee();
        safetyUser.setId(originalEmployee.getId());
        safetyUser.setUsername(originalEmployee.getUsername());
        safetyUser.setName(originalEmployee.getName());
        safetyUser.setPhone(originalEmployee.getPhone());
        safetyUser.setSex(originalEmployee.getSex());
        safetyUser.setIdNumber(originalEmployee.getIdNumber());
        safetyUser.setStatus(originalEmployee.getStatus());
        safetyUser.setCreateTime(originalEmployee.getCreateTime());
        safetyUser.setUpdateTime(originalEmployee.getUpdateTime());
        safetyUser.setCreateUser(0L);//todo
        safetyUser.setUpdateUser(0L);//todo

        return safetyUser;
    }
}
